<template>
  <view class="container">
    <custom-navbar :immersive="true" title="登录" color="#333"> </custom-navbar>
    <view class="container_header" :style="{ paddingTop: `${navbarHeight}px` }">
      <image class="container_header_logo" src="/static/image/logo.png" mode="aspectFill" />
    </view>
    <view class="container_content">
      <button class="container_content_login" v-if="!agreement" @click="checkAgreement">
        <!-- <image class="container_content_login_icon" src="/static/image/login_wechat_icon.png" mode="widthFix" /> -->
        <text>立即登录</text>
      </button>
      <button class="container_content_login" v-else open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
        <!-- <image class="container_content_login_icon" src="/static/image/login_wechat_icon.png" mode="widthFix" /> -->
        <text>立即登录</text>
      </button>
      <view class="container_content_tip">*若手机号尚未注册，将自动为您创建账号</view>

      <view class="container_content_secret">
        <checkbox-group @change="agreementChange" class="container_content_secret_check">
          <label class="checkbox-container">
            <checkbox class="container_content_secret_check_checkbox" :class="agreement ? 'checked' : ''" value="1" :checked="agreement" style="opacity: 0; position: absolute" />
            <uni-icons class="selected-icon" :type="agreement?'checkbox-filled':'circle'" size="21" :color="agreement?'#28bc56':''"></uni-icons>

            我已阅读并同意
            <text @click="showPrivacy" class="text-green"> 《隐私条款》 </text>
            及
            <text @click="showProtocol" class="text-green"> 《服务协议》 </text>
          </label>
        </checkbox-group>
      </view>
    </view>

    <!-- <view class="container_header">
      <image src="https://bw000.zjjqf.cn/file/000upload/image/login_header.png" mode="widthFix" class="container_header_pic" />
    </view>
    <view class="container_form">
      <view class="container_form_row">
        <view class="container_form_row_label">手机号</view>
        <input class="container_form_row_value" placeholder="请输入手机号" v-model="formData.userPhone" />
      </view>
      <view class="container_form_row">
        <view class="container_form_row_label">密码</view>
        <view class="flex container_form_row_value j-content-between">
          <input placeholder="请输入密码" v-model="formData.userPassward" :password="iconType !== 'eye'" />
          <uni-icons :type="iconType" color="#999" size="20" @click="changePassType" />
        </view>
      </view>
          <view @click="goRegister" class="container_form_register">注册</view>
      <button class="container_form_login-btn" @click="handleLogin">登录</button>

      <view class="container_form_secret">
        <checkbox-group @change="agreementChange" class="container_form_secret_check">
          <checkbox class="blue" :class="agreement ? 'checked' : ''" value="1" :checked="agreement" style="transform: scale(0.7)" />
          我已阅读并同意
          <text @click="showPrivacy" class="text-green"> 《隐私条款》 </text>
          及
          <text @click="showProtocol" class="text-green"> 《服务协议》 </text>
        </checkbox-group>
      </view>
      <view class="container_form_orange"><image src="https://bw000.zjjqf.cn/file/000upload/image/login_orange.png" mode="widthFix" /></view>
    </view> -->

    <!-- <view class="container_wechat">
      <view class="container_wechat_title">
        <view class="container_wechat_title_line"></view>
        <view class="container_wechat_title_txt">社交账号登录</view>
        <view class="container_wechat_title_line"></view>
      </view>
      <view class="container_wechat_icon" @click="goWechatLogin">
        <image src="/static/image/wechat_icon.png" mode="widthFix" />
      </view>
    </view> -->
  </view>
</template>

<script>
import { getToken, setToken, setUserInfo, getCompanyLogo } from '@/service/auth.js'
import navmixin from '@/mxins/nav.js'
import { API_login, appletCheckIsRegister, wxLogin } from '@/service/api/login.js'
import { encrypt } from '@/utils/func.js'
import { getLoginOpenId } from '@/service/api/wx'
import { getOpenId, getPhone, setOpenId, setSessionKey } from '@/service/auth'
import jPopup from '@/components/jPopup'
import navbarMixin from '@/mxins/navbar.js'
import { appletInviteRegister } from '@/service/api/register'
export default {
  components: { jPopup },
  mixins: [navbarMixin],
  data() {
    return {
      formData: {
        userPhone: '',
        userPassward: '',
      },
      showPop: false,
      mask: false,
      companyList: [],
      showCompanyName: '',
      companyCode: '000',
      information: {},
      logo: '',
      agreement: false, //隐私协议
      inputStyle: {
        backgroundColor: '#ff000f',
        // boxShadow: ' 0 1px 5px rgba(0, 0, 0, 0.06)',
        borderRadius: '10px',
      },
      iconType: 'eye-slash',
    }
  },
  watch: {
    'formData.userPhone'(n, o) {
      // if (this.formData.userPhone.length === 11) {
      //   this.selectCompany()
      // }
    },
  },
  created() {
    this.logo = getCompanyLogo(wx.getAccountInfoSync().miniProgram.appId)
    uni.getSystemInfo({
      success: function (res) {
        console.log(res)
      },
    })
    this.formData.userPhone = uni.getStorageSync('userPhone')
    this.formData.userPassward = uni.getStorageSync('userPassward')
    this.getWxOpenId()
  },
  onLoad(option) {
    if (option.token) {
      const user = JSON.parse(option.user)
      const token = option.token
      setToken(token)
      setUserInfo(user)
      const app = getApp()
      const customer = user.customerList[0]
      if (customer) app.globalData.selectedPosition = { id: customer.customerId, name: customer.customerName }
      uni.switchTab({
        url: '/pages/home/index',
      })
      return
    }
    this.agreement = uni.getStorageSync('loginAgreement')
    if (option.information) {
      // this.information = JSON.parse(option.information)
      // this.wxlogin(this.information.companyCode)
      // const username = uni.getStorageSync('userPhone')
      // //判断是否有历史登录
      // const historyCompany = uni.getStorageSync('companyCode')
      // if (username && historyCompany === this.information.companyCode) {
      //   const password = uni.getStorageSync('userPassward') || '123456'
      //   let pData = { username: username, password: password, companyCode: this.information.companyCode }
      //   //尝试登录
      //   this.login(pData)
      // } else {
      //   this.showPop = true
      //   this.mask = true
      // }
    }
  },
  methods: {
    async getWxOpenId() {
      const _that = this
      const wxCode = await this.getWxCode()
      getLoginOpenId({ code: wxCode, companyCode: '000' }).then(val => {
        if (val.status === 200) {
          console.log(`当前获取openid为${val.data.openid}`)
          setOpenId(val.data.openid, '000')
          setSessionKey(val.data.session_key)
        }
      })
    },
    changePassType() {
      this.iconType = this.iconType === 'eye' ? 'eye-slash' : 'eye'
    },
    async getWxCode() {
      return new Promise((resolve, reject) => {
        wx.login().then(res => {
          resolve(res.code)
        })
      })
    },
    async selectCompany() {
      const { userPhone, userPassward } = this.formData
      if (userPhone.length !== 11) {
        uni.showModal({ title: '提示', content: '请输入正确手机号' })
        return false
      }
      let pData = { username: userPhone, password: encrypt(userPassward) }
      API_login(pData)
        .then(res => {
          this.companyList = res.data.companyList
          this.companyCode = this.companyList[0].companyCode
          this.showCompanyName = this.companyList[0].companyName
          if (this.companyList.length === 1 && uni.getStorageSync('voluntarilyLogin') === 'true') this.voluntarilyLogin()
        })
        .catch(err => {
          this.companyList = []
          this.companyCode = ''
          this.showCompanyName = ''
        })
    },
    //自动登录
    voluntarilyLogin() {
      const password = uni.getStorageSync('userPassward') || '123456'
      let pData = { username: this.formData.userPhone, password: password, companyCode: uni.getStorageSync('companyCode') }
      this.login(pData)
    },
    setCompany(item) {
      this.showCompanyName = item.companyName
      this.companyCode = item.companyCode
    },
    //登录
    async login(pData) {
      const data = Object.assign({}, pData)
      data.password = encrypt(pData.password)
      uni.showLoading({ title: '正在登录' })
      const res = await API_login(data).catch(err => {
        console.log('err' + JSON.stringify(err))
        if (err.status !== 200) {
          this.uniHideLoading()
          uni.showModal({ title: '提示', content: '账号或密码错误' })
        }
      })
      this.uniHideLoading()
      const {
        status,
        data: { token, user },
      } = res
      console.log('status', status)
      if (status == 200) {
        // 存储token 和 userInfo
        uni.setStorageSync('userPhone', pData.username)
        uni.setStorageSync('userPassward', pData.password)
        uni.setStorageSync('companyCode', pData.companyCode)
        uni.setStorageSync('voluntarilyLogin', 'true')
        setToken(token)
        setUserInfo(user)
        const app = getApp()
        const customer = user.customerList[0]
        if (customer) app.globalData.selectedPosition = { id: customer.customerId, name: customer.customerName }

        console.log('switchTab')
        uni.switchTab({
          url: '/pages/home/index',
        })
      }
    },
    checkAgreement() {
      if (!this.agreement) return this.uniShowToast('请先同意用户隐私协议')
    },

    async onGetPhoneNumber(e) {
      console.log('e', e)
      const _that = this

      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        const phone = getPhone(e.detail.encryptedData, e.detail.iv)
        const userPhone = phone.phoneNumber

        const wxCode = await this.getWxCode()
        uni.showLoading({ title: '正在登录' })

        const param = {
          phone: userPhone,
          wxCode: wxCode,
        }
        console.log('param' + JSON.stringify(param))

        appletInviteRegister(param)
          .then(res => {
            _that.uniHideLoading()
            const {
              status,
              data: { token, user },
            } = res

            if (status == 200) {
              setToken(token)
              setUserInfo(user)
              uni.switchTab({
                url: '/pages/home/index',
              })
            }
          })
          .catch(err => {
            _that.uniHideLoading()
            _that.uniShowToast(err.msg)
          })
      } else {
        _that.uniShowToast('获取手机号失败')
      }
    },
    upCompany(e) {
      const { value } = e.target
      let company = this.companyList[value]
      this.showCompanyName = company.companyName
      this.companyCode = company.companyCode
    },

    // 账号密码 登录
    async handleLogin() {
      const { userPhone, userPassward } = this.formData
      if (!userPhone) return this.uniShowToast('请输入手机号')
      if (!userPassward) return this.uniShowToast('请输入密码')
      if (!this.agreement) return this.uniShowToast('请先同意用户隐私协议')
      this.uniShowLoading()

      let pData = { username: userPhone, password: userPassward, companyCode: '000' }
      // let ppData = { Authorization: '', authUser: pData }
      await this.login(pData)
    },

    close() {
      this.showPop = false
      this.mask = false
    },
    async goWechatLogin() {
      const that = this
      if (!that.agreement) return that.uniShowToast('请先同意用户隐私协议')
      that.uniShowLoading()
      const companyCode = '000'
      const wxCode = await this.getWxCode()
      wxLogin({ code: wxCode, companyCode })
        .then(res => {
          console.log('res', res)
          const {
            status,
            data: { token, user },
          } = res
          console.log('status', status)
          if (status == 200) {
            setToken(token)
            setUserInfo(user)
            uni.switchTab({
              url: '/pages/home/index',
            })
          }
          this.uniHideLoading()
        })
        .catch(err => {
          that.uniHideLoading()

          if (err.msg && err.msg.includes('未绑定')) {
            uni.showModal({
              title: '提示',
              content: '微信未绑定，请先注册',
              success: function (res) {
                if (res.confirm) {
                  that.goRegister()
                }
              },
            })
          } else {
            that.uniShowToast(err.msg)
          }
        })
    },
    agreementChange(e) {
      this.agreement = e.detail.value[0] === '1'
      uni.setStorage({
        key: 'loginAgreement',
        data: this.agreement,
        success: () => {},
      })
    },
    showPrivacy() {
      this.$Router.push({
        name: 'protocol',
        params: {
          mode: 'privacy',
        },
      })
    },
    showProtocol() {
      this.$Router.push({
        name: 'protocol',
        params: {
          mode: 'protocol',
        },
      })
    },
    goRegister() {
      uni.navigateTo({
        url: `/pages/register/index`,
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(155deg, #cdefd8 1%, #f6f6f6 20%, #f6f6f6 90%);
  &_header {
    flex: 2;
    display: flex;
    align-items: center;
    &_logo {
      width: 300rpx;
      margin: 0 auto;
    }
  }
  &_content {
    flex: 2;
    &_login {
      background: linear-gradient(to right, #75e398, #28bc56);
      margin: 30rpx 40rpx;
      border-radius: 50rpx;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 32rpx;
      &_icon {
        width: 40rpx;
        height: 40rpx;
        margin-right: 10rpx;
      }
    }
    &_btn-register {
      border-radius: 50rpx;
      border: 1rpx solid #edeff4;
      height: 88rpx;
      font-size: 28rpx;
      color: #999;
      margin: 40rpx 40rpx;
    }
    &_tip {
      margin: 30rpx 50rpx;
      color: #999;
      font-size: 24rpx;
    }
    &_secret {
      display: flex;
      margin:10rpx 50rpx;
      font-size: 26rpx;
      color: #9098a5;
      &_check_checkbox {
        width: 30rpx;
        height: 30rpx;
        border-radius: 50%;
      }
      .checkbox-container {
        display: flex;
        align-items: center;
      }
      .custom-checkbox {
        width: 30rpx;
        height: 30rpx;
        border-radius: 50%;
        border: 2rpx solid #ccc;
        margin-right: 16rpx;
        position: relative;
        transition: all 0.3s;
      }
      .custom-checkbox.checked {
        border-color: #2bbe59;
        background-color: #2bbe59;
      }

      .custom-checkbox.checked::after {
        content: '';
        position: absolute;
        width: 16rpx;
        height: 16rpx;
        border-radius: 50%;
        background: white;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
  }
  /* &_header {
    background: linear-gradient(to bottom, #2bbe59, #f6f6f6);
    height: 450rpx;
    padding-top: 50rpx;
    &_pic {
      width: 100%;
    }
  }
  &_form {
    position: relative;
    flex: 1;
    background-color: #f6f6f6;
    margin-top: -50rpx;
    border-top-left-radius: 50rpx;
    border-top-right-radius: 50rpx;
    padding: 20rpx;

    &_row {
      margin-top: 30rpx;

      &_value {
        background-color: white;
        border-radius: 10rpx;
        height: 70rpx;
        align-items: center;
        padding-left: 10rpx;
        margin-top: 10rpx;
        box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.06);
      }
    }
    &_register {
      margin-top: 40rpx;
      text-align: right;
    }
    &_login-btn {
      background: linear-gradient(to left, #26bb55, #77e399);
      color: white;
      margin-top: 40rpx;
    }
    &_secret {
      position: fixed;
      display: flex;
      bottom: 40rpx;
      left: 0;
      right: 0;
      font-size: 26rpx;
      &_check {
        margin: 0 auto;
      }
    }
    &_orange {
      position: absolute;
      top: -150rpx;
      right: 0;
      width: 250rpx;
    }
  }
  &_wechat {
    flex: 1;
    &_title {
      display: flex;
      align-items: center;
      color: #999;
      &_line {
        height: 2rpx;
        background-color: #edeff4;
        flex: 1;
      }
      &_txt {
        margin: 0 20rpx;
      }
    }
    &_icon {
      width: 80rpx;
      height: 80rpx;
      margin: 20rpx auto;
    }
  } */
}
button::after {
  border: none;
}
</style>
